package socket;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;


public class SocketTest {
    public SocketTest() {

        Thread t = new reThread();
        t.start();
    }

    public static void main(String[] args) {
        new SocketTest();
    }
}

class reThread extends Thread {

    InetSocketAddress inetSocketAddress = new InetSocketAddress("192.168.13.77", 37810);

    String strCameraInfo = "20000000444849500000000000000000490000000000000049000000000000007b20226d6574686f6422203a20224448446973636f7665722e736561726368222c2022706172616d7322203a207b20226d616322203a2022222c2022756e6922203a2031207d207d0a";
    String serverInfo = "6a614b00";

    public void run() {

        try {
            //DatagramSocket socket = new DatagramSocket(37810);
            DatagramSocket socket = new DatagramSocket(27418);

            // InetSocketAddress isa = new InetSocketAddress("192.168.13.77", 37810);

            while (true) {

                //byte[] bytes = hexToBytes(strCameraInfo);
                byte[] bytes = hexToBytes(serverInfo);
                DatagramPacket packet = new DatagramPacket(bytes, bytes.length, inetSocketAddress);
                socket.send(packet);

                bytes = new byte[1024];
                DatagramPacket packet2 = new DatagramPacket(bytes, bytes.length);
                socket.receive(packet2);
                String m = new String(bytes, 0, packet2.getLength(), "utf-8");
                System.out.println("message:" + m);
            }

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

    }

    public byte[] hexToBytes(String hex) {
        hex = hex.length() % 2 != 0 ? "0" + hex : hex;

        byte[] b = new byte[hex.length() / 2];
        for (int i = 0; i < b.length; i++) {
            int index = i * 2;
            int v = Integer.parseInt(hex.substring(index, index + 2), 16);
            b[i] = (byte) v;
        }
        return b;
    }

}
